package com.wjh.www.controller.filters;

import com.wjh.www.controller.constant.HeaderConstant;
import com.wjh.www.controller.util.DoFilterUtil;
import com.wjh.www.entity.bo.TokenBo;
import com.wjh.www.entity.dto.CommonResult;
import com.wjh.www.entity.dto.ResultUtil;
import com.wjh.www.util.LoggerUtil;
import com.wjh.www.util.SecurityUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

/**
 * 接口权限鉴定
 *
 * @author wjh
 */
@WebFilter("/*")
public class SystemFilter implements Filter {
    private final Logger logger = LoggerUtil.getLogger();

    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求路径
        String url = request.getRequestURI();
        logger.info("经过拦截器的url：" + url);
        //可放行的接口
        List<String> list = DoFilterUtil.getDoFilterList();
        //要访问的接口
        String methodName = url.substring(url.lastIndexOf("/"));
        if (list.contains(methodName)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        if (request.getHeader(HeaderConstant.MY_TOKEN) != null) {
            TokenBo tokenBo = SecurityUtil.decodeToken(request.getHeader(HeaderConstant.MY_TOKEN));
            logger.info("本次请求的tokenBo：" + tokenBo);
            List<String> permissionList = tokenBo.getPermissionList();
            //没有权限
            if (!permissionList.contains(methodName)) {
                logger.info("没有权限访问：" + url);
                ResultUtil.printCode(response, CommonResult.operateFailWithMessage("您没有权限访问该接口"), 401);
            }
            //token过期
            if (System.currentTimeMillis() > tokenBo.getExpireAt()) {
                logger.info("token已经过期了");
                ResultUtil.printCode(response, CommonResult.operateFailWithMessage("权限已过期，请重新登录"), 401);
            }
        }
        if (request.getHeader(HeaderConstant.MY_TOKEN) == null) {
            logger.info("没有权限访问：" + url);
            ResultUtil.printCode(response, CommonResult.operateFailWithMessage("您没有权限访问该接口"), 401);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
